﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace KB
{
    public class CookieUtility
    {
        /// <summary>
        ///  
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="expiresMin">if setting int.MaxValue, it will be endless</param>
        public static void SetCookie(string name, string value, int expiresMin = 0, string domain = "")
        {
            var cookie = new HttpCookie(name);
            cookie.Value = value;
            if (expiresMin > 0)
            {
                if (expiresMin == int.MaxValue)
                {
                    cookie.Expires = DateTime.MaxValue;
                }
                else
                {
                    cookie.Expires = DateTime.Now.AddMinutes(expiresMin);
                }
            }
            if (domain != "")
            {
                cookie.Domain = domain;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }


        public static string GetCookie(string name)
        {
            return HttpContext.Current.Request.Cookies[name] == null
                       ? ""
                       : HttpContext.Current.Request.Cookies[name].Value;
        }

        public static void ClearCookie(string name)
        {
            var cookie = HttpContext.Current.Request.Cookies[name];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1D);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }
    }
}
